#include "mlist.h"

void mlist_init(mlist_t *list, void *used, void *items, mlist_list_size_t size, mlist_data_size_t data_size)
{
    mlist_list_size_t index;

    list->size = size;
    list->data_size = data_size;
    list->used = used;
    list->data = items;

    for(index = 0; index < size; index++)
    {
        list->used[index] = 0;
    }
}

void *mlist_find(mlist_t *list, mlist_find_func_t findFunc, mlist_list_size_t *index, void *userdata)
{
    unsigned char *item;
    mlist_list_size_t i;

    for(i = 0; i < list->size; i++)
    {
        if(!list->used[i])
        {
            continue;
        }

        item = list->data + i * list->data_size;

        if(findFunc(item, userdata))
        {
            *index = i;
            return item;
        }
    }

    return NULL;
}

void mlist_foreach(mlist_t *list, mlist_foreach_func_t foreachFunc)
{
    unsigned char *item;
    mlist_list_size_t i;

    for(i = 0; i < list->size; i++)
    {
        if(!list->used[i])
        {
            continue;
        }

        item = list->data + i * list->data_size;

        if(foreachFunc(item, i))
        {
            break;
        }
    }
}

mlist_list_size_t mlist_add(mlist_t *list, void *item, mlist_data_size_t len)
{
    unsigned char *data = NULL;
    mlist_list_size_t i;
    mlist_data_size_t j;

    for(i = 0; i < list->size; i++)
    {
        if(list->used[i])
        {
            continue;
        }

        list->used[i] = 1;
        data = list->data + i * list->data_size;
        break;
    }

    if(i == list->size)
    {
        return -1;
    }

    if(data != NULL && item != NULL)
    {
        for(j = 0; j < list->data_size && j < len; j++)
        {
            data[j] = ((unsigned char *)item)[j];
        }
    }

    return i;
}

void mlist_del(mlist_t *list, mlist_list_size_t index)
{
    if(index >=  list->size || index < 0)
    {
        return;
    }

    list->used[index] = 0;
}

void *mlist_get(mlist_t *list, mlist_list_size_t index)
{
    if(index > list->size || index < 0)
    {
        return NULL;
    }

    if(!list->used[index])
    {
        return NULL;
    }

    return list->data + index * list->data_size;
}
